package Test03;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomDemo {
	private static Document document;

	public static void main(String[] args) {
		getDocument();
		showInfo();
		//add();
		// delete();
//		update();
	}

	// 保存xml文件
	private static void saveXml() {
		TransformerFactory factory = TransformerFactory.newInstance();
		factory.setAttribute("indent-number", "40");
		try {
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//			StreamResult result=new StreamResult(new FileOutputStream(path));
			StreamResult result = new StreamResult(
					new OutputStreamWriter(new FileOutputStream("resources/Phones.xml"), "utf-8"));
			DOMSource source = new DOMSource(document);
			transformer.transform(source, result);
			System.out.println("保存成功!");
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void add() {
		// 创建mobile节点
		Element element = document.createElement("mobile");
		element.setAttribute("name", "苹果");
		// 创建Type节点
		Element childElement = document.createElement("name");
		childElement.setTextContent("三星");
		Element childElement2 = document.createElement("price");
		childElement2.setTextContent("6888");
		Element childElement3 = document.createElement("type");
		childElement3.setTextContent("5G");
		
		// 把Type节点作为Brand子节点
		element.appendChild(childElement);
		element.appendChild(childElement2);
		element.appendChild(childElement3);
		// 把Brand节点作为根节点的子节点
		document.getElementsByTagName("phones").item(0).appendChild(element);
		// 保存文件
		saveXml();
	}

	// 修改
	private static void update() {
		NodeList brands = document.getElementsByTagName("mobile");
		for (int i = 0; i < brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element eleBrand = (Element) brand;
			eleBrand.setAttribute("name", i + "");
		}
		
		
		saveXml();
	}

	private static void showInfo() {
		// 查找Brand标签,返回NodeList集合
		NodeList nodeList = document.getElementsByTagName("mobile");
		// 循环NodeList(也就是循环所有的Brand标签)
		for (int i = 0; i < nodeList.getLength(); i++) {
			// 通过索引获取Node对象
			Node node = nodeList.item(i);
			/*
			 * 将Node对象转换成Element类型 因为Element继承于Node,而且Element有getAttribute方法可以根据属性名得到属性值
			 */
			Element element = (Element) node;
			System.out.println(element.getAttribute("name"));
			// 获得该元素下的所有子节点
			NodeList childNodeList = element.getChildNodes();
			for (int j = 0; j < childNodeList.getLength(); j++) {
				Node childNode = childNodeList.item(j);
				// 判断节点是否是元素节点
				if (childNode.getNodeType() == Node.ELEMENT_NODE) {
					// 获得节点名称
					String nodeName = childNode.getNodeName();
					// 得到该节点下的文本内容
					String val = childNode.getTextContent();
					System.out.println(nodeName + ":" + val);
				}
			}

		}
	}

	// 加载xml返回Document对象
	private static void getDocument() {
		/*
		 * DocumentBuilderFactory->DocumentBuilder->Document
		 */
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			// 解析xml文件,返回Document对象
			document = builder.parse("resources/Phones.xml");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}

	// 删除
	public static void delete() {
		NodeList brands = document.getElementsByTagName("mobile");
		for (int i = 0; i < brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element eleBrand = (Element) brand;
			if (eleBrand.getAttribute("name").equals("三星")) {
				eleBrand.getParentNode().removeChild(eleBrand);
			}
		}
		saveXml();
	}
}
